<template>
  <div :class="{ 'has-logo': showLogo }">
    <Logo v-if="showLogo" :collapse="isCollapse" />
    <el-scrollbar wrap-class="scrollbar-wrapper">
      <el-menu :default-active="activeMenu" :collapse="isCollapse" :background-color="variables.menuBg"
        :text-color="variables.menuText" :unique-opened="true" :active-text-color="variables.activeMenuText"
        :collapse-transition="false" mode="vertical">
        <SidebarItem v-for="route in perm_routes" :key="route.path" :item="route" :base-path="route.path" />
      </el-menu>
    </el-scrollbar>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import Logo from "./Logo";
import SidebarItem from "./SidebarItem";
import variables from "@/styles/variables.scss";
import UserApi from "@/api/system-settings/user-manage";

export default {
  data () {
    return {
      //所有授权的路由（页面上渲染的）
      perm_routes: []
    }
  },
  components: { SidebarItem, Logo },
  mounted () {
    console.log('sidebarmounted........')
    this.authPermissionRoutes()
    // console.log(permission_routes);
  },
  methods: {
    authPermissionRoutes () {
      UserApi.queryAllPermissionList({ funcType: 'OMS' }).then(res => {
        let auth_routes = this.transformRoutes(res.data.functionPermissionMap.OMS)
        let routes = this.permission_routes
        for (let path of auth_routes)
        {
          this.formatRoutes(routes, path)
        }
        this.perm_routes = routes
      })
    },
    //将所有路由对象转为路径的数组
    transformRoutes (routes, rst = []) {
      routes.forEach(route => {
        rst.push(route.component)
        if (route.childList)
        {
          this.transformRoutes(route.childList, rst)
        }
      })
      return rst
    },
    //给有权限的路由授权
    formatRoutes (perm_routes, path) {
      let self = this
      perm_routes.forEach((item) => {
        if (item.path == path)
        {
          if (item.meta)
          {
            item.meta.auth = true
          } else
          {
            item.meta = {}
            item.meta.auth = true
          }
        } else
        {
          if (item.children && item.children.length > 0)
          {
            self.formatRoutes(item.children, path)
          } else
          {
            return false
          }
        }
      })
    }
  },
  computed: {
    ...mapGetters(["permission_routes", "sidebar"]),

    routes () {
      return this.$router.options.routes;

    },
    activeMenu () {
      const route = this.$route;
      const { meta, path } = route;
      // if set path, the sidebar will highlight the path you set
      if (meta.activeMenu)
      {
        return meta.activeMenu;
      }
      return path;
    },
    showLogo () {
      return this.$store.state.settings.sidebarLogo;
    },
    variables () {
      return variables;
    },
    isCollapse () {
      return !this.sidebar.opened;
    }
  }
};
</script>
